# -*- coding:utf-8 -*-
## author : cypro666
## note   : python3.4+
"""
a group of 'system command calling' wrappers 
only support linux os
"""
import time, sys
from subprocess import Popen, PIPE

__all__ = ['SysCommand']


class SysCommand(object):
    """ all methods are static """
    @staticmethod
    def execute(cmd, show = False):
        """ execute system command using Popen and return the result str """
        output = Popen(cmd, shell=True, stdout=PIPE)
        if show:
            sys.stdout.write(cmd+'\n')
        return str(output.stdout.read(), 'utf-8')

    @staticmethod
    def popen(cmd, show = False):
        """ same as execute, but return stdout of pipe """
        output = Popen(cmd, shell=True, stdout=PIPE)
        if show:
            sys.stdout.write(cmd+'\n')
        return output.stdout

    @staticmethod
    def count_process(keyword, show = False):
        """ count process specified in `keyword` using 'ps' system command """
        output = Popen('ps ax | egrep %s' % keyword, shell=True, stdout=PIPE)
        lines = []
        for line in output.stdout:
            line = str(line, 'utf-8')
            if keyword in line and 'grep ' not in line:
                lines.append(line)
        return len(lines), tuple(lines)

    @staticmethod
    def count_process_ex(keyword, exclude, show = False):
        """ like count_process, but exclude `exclude` """
        output = Popen('ps ax | egrep %s' % keyword, shell=True, stdout=PIPE)
        lines = []
        for line in output.stdout:
            line = str(line, 'utf-8')
            if keyword in line and exclude not in line and 'grep ' not in line:
                lines.append(line)
        return len(lines), tuple(lines)

    @staticmethod
    def getpid(keyword, show = False):
        """ getpid """
        output = Popen('pgrep %s' % keyword, shell=True, stdout=PIPE)
        pid = 0
        for line in output.stdout:
            pid = int(str(line, 'utf-8'))
        return pid



def test():
    r = SysCommand.execute('ls -al')
    print(r)
    
    n , r = SysCommand.count_process('python3')
    print(n)
    for item in r:
        print(item, end='')

    n, r = SysCommand.count_process_ex('python3', 'pydev')
    print(n)
    for item in r:
        print(item, end='')

    print(SysCommand.getpid('syscommand.py'))
    
    for i in range(5):
        print(SysCommand.execute('uptime'), end="")
        print(SysCommand.execute('free -mo'))
        time.sleep(1.0)


if __name__ == '__main__':
    test() 

